#include "dialoglogin.h"
#include "ui_dialoglogin.h"
#include "appsettings.h"
#include <QStyledItemDelegate>
#include "Account.h"


DialogLogin::DialogLogin(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::DialogLogin)
{
    ui->setupUi(this);

    QStyledItemDelegate* itemDelegate = new QStyledItemDelegate();
    ui->comboBox->setItemDelegate(itemDelegate);
    ui->comboBox->setStyleSheet("QComboBox QAbstractItemView::item {min-height: 28px;}");

	ui->labelError->hide();
}

DialogLogin::~DialogLogin()
{
    delete ui;
}

void DialogLogin::on_pushButtonLogin_clicked()
{
	ui->labelError->hide();

	QString name = ui->comboBox->currentText();
	QString password = ui->lineEdit->text();
	
	if (checkAccount(name, password))
	{
		accept();
	}
	else
	{
		ui->labelError->show();
	}
}

void DialogLogin::setDataStore(std::shared_ptr< SecureDataStore>& dataStore)
{
	m_dataStore = dataStore;

	QString title = AppSettings::getString("App/Title", "");
	ui->labelTitle->setText(title);

	std::vector< std::string >	users;
	m_dataStore->getKeys(users);

	//for (size_t i = 0; i < users.size(); ++i)
	//{
	//	std::string& user = users[i];
	//	ui->comboBox->addItem(user.c_str());
	//}
		
    ui->comboBox->addItem(Account::ADMIN);
}

bool DialogLogin::checkAccount(const QString& name, const QString& password)
{
	std::string value;
    if (!m_dataStore->getValue(name.toStdString(), value))
    {
        return false;
    }
	return value == password.toStdString();
}

QString DialogLogin::getUser()
{
    return ui->comboBox->currentText();
}
